/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.deliveryticket;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.TransactionValidate;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.WmDeliveryTicketLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsDeliveryTicketLineMapper;
import com.lightkits.wms.database.dao.WmsDeliveryTicketMapper;
import com.lightkits.wms.database.model.DeliveryTicketLineModel;
import com.lightkits.wms.database.model.WmSimTicketModel;
import com.lightkits.wms.domain.usuallyinterface.GetWmMoveTypeExecutor;
import com.lightkits.wms.dto.deliveryticket.QueryDeliveryTicketRequestType;
import com.lightkits.wms.dto.deliveryticket.QueryDeliveryTicketResponseType;
import com.lightkits.wms.dto.deliveryticket.models.DeliveryTicketLineDTO;
import com.lightkits.wms.dto.deliveryticket.models.DeliveryTicketViewDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * QueryDeliveryTicketExecutor
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/19 17:12
 */
@Component
public class QueryDeliveryTicketExecutor implements ServiceExecutor<QueryDeliveryTicketRequestType, QueryDeliveryTicketResponseType> {
    private static final Logger LOGGER = LoggerFactory.getLogger(GetWmMoveTypeExecutor.class);

    private final WmsDeliveryTicketMapper wmDeliveryTicketMapper;
    private final WmsDeliveryTicketLineMapper wmDeliveryTicketLineMapper;

    @Autowired
    public QueryDeliveryTicketExecutor(WmsDeliveryTicketMapper wmDeliveryTicketMapper, WmsDeliveryTicketLineMapper wmDeliveryTicketLineMapper) {
        this.wmDeliveryTicketMapper = wmDeliveryTicketMapper;
        this.wmDeliveryTicketLineMapper = wmDeliveryTicketLineMapper;
    }

    /**
     * 送货单查询
     *
     * @param request 送货单查询请求参数
     * @return
     */
    @Override
    public QueryDeliveryTicketResponseType service(QueryDeliveryTicketRequestType request) {
        QueryDeliveryTicketResponseType response = new QueryDeliveryTicketResponseType();
        response.setSuccessful(true);
        try {
            //参数非空校验（送货单id或者单据号不能为空）
            IntegrityValidator.begin()
                    .validate(request.getTicketIdOrNum(), "TicketId or TicketNum");
            //参数有效性校验
            TransactionValidate check1 = TransactionValidate.beginValidity(WmDeliveryTicketLine.class);
            check1.checkIdValidity(ObjectUtil.toString(request.getTicketLineId()), "ID");
            //根据参数获取送货单头
            List<WmSimTicketModel> headModels = wmDeliveryTicketMapper.queryTicketByIdOrNum(request.getTicketIdOrNum());
            if (ObjectUtil.isNullOrEmpty(headModels) || headModels.size() != 1) {
                response.setSuccessful(false);
                response.setMessage("the ticketNumOrId is invalid");
                return response;
            }
            DeliveryTicketViewDTO viewDTO = convertHead(headModels.get(0));
            response.setTicketHeadDto(viewDTO);
            //根据请求参数获取送货单行信息
            List<DeliveryTicketLineModel> lineModels = wmDeliveryTicketLineMapper
                    .queryTicketLineByParams(request.getTicketIdOrNum(), request.getTicketLineId());
            if (ObjectUtil.isNullOrEmpty(lineModels)) {
                response.setTicketLineDTOS(new ArrayList<>());
                return response;
            }
            if (!ObjectUtil.isNullOrEmpty(request.getTicketLineId()) && lineModels.size() != 1) {
                response.setSuccessful(false);
                response.setMessage("the ticketLineId is not unique");
                return response;
            }
            response.setTicketLineDTOS(convertLine(lineModels));
        } catch (LightKitsBizException e) {
            response.setSuccessful(false);
            String mes = StringUtils.substringAfterLast(e.getMessage(), ":");
            response.setMessage(ObjectUtil.isNullOrEmpty(mes) ? e.getMessage() : mes);
        } catch (Exception e) {
            e.printStackTrace();
            response.setSuccessful(false);
            response.setMessage("get Simple Ticket Message Error");
        }
        return response;
    }

    /**
     * 转换送货单头
     *
     * @param model 送货单头信息
     * @return
     */
    private DeliveryTicketViewDTO convertHead(WmSimTicketModel model) {
        DeliveryTicketViewDTO viewDTO = new DeliveryTicketViewDTO();
        try {
            viewDTO.setOrgId(model.getOrgId());
            viewDTO.setOrgName(model.getOrgName());
            viewDTO.setPartyId(model.getPartyId());
            viewDTO.setPartyName(model.getPartyName());
            viewDTO.setPartySiteId(model.getPartySiteId());
            viewDTO.setPartySiteName(model.getPartySiteName());
            viewDTO.setTicketId(model.getTicketId());
            viewDTO.setTicketNum(model.getTicketNum());
            viewDTO.setTicketStatus(model.getTicketStatus());
            viewDTO.setWorkerName(model.getWorkerName());
            viewDTO.setAddress(model.getAddress());
            viewDTO.setPhoneNumber(model.getPhoneNumber());
            viewDTO.setContact(model.getContact());
            viewDTO.setWorkerNum(model.getWorkerNum());
        } catch (Exception e) {
            LOGGER.error("convertHead.error", e);
            throw new LightKitsBizException(e);
        }
        return viewDTO;
    }

    /**
     * 转换送货单行信息
     *
     * @param lineModels 送货单行信息
     * @return
     */
    private List<DeliveryTicketLineDTO> convertLine(List<DeliveryTicketLineModel> lineModels) {
        List<DeliveryTicketLineDTO> dtos = new ArrayList<>();
        try {
            lineModels.forEach(model -> {
                DeliveryTicketLineDTO dto = new DeliveryTicketLineDTO();
                dto.setTicketLineId(model.getTicketLineId());
                dto.setItemId(model.getItemId());
                dto.setItemCode(model.getItemCode());
                dto.setItemDesc(model.getItemDesc());
                FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                        .eq(FndUomBase.UOM_CODE, model.getUomName()));
                if (ObjectUtil.isEmpty(uomBase)) {
                    dto.setReceivedQty(model.getReceivedQty().toString());
                } else {
                    dto.setReceivedQty(model.getReceivedQty()
                            .setScale(uomBase.getDecimalNumber().intValue()
                                    , BigDecimal.ROUND_HALF_UP).toString());
                }
                dto.setUomName(model.getUomName());
                dto.setWarehouseName(model.getReceiveWarehouseName());
                dto.setWmAreaName(model.getReceiveWmAreaName());
                dto.setPoNum(model.getPoNum());
                dto.setPartyLotCode(model.getPartyLotCode());
                dtos.add(dto);
            });
        } catch (Exception e) {
            LOGGER.error("convertLine.error", e);
            throw new LightKitsBizException(e);
        }
        return dtos;
    }
}
